package com.sa07.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.DatagramChannel;

import org.apache.log4j.Logger;

import com.sa07.bean.UserArgsConstant;
import com.sa07.config.UserArgsConfig;
import com.sa07.exception.IllegalConnectStateException;
import com.sa07.exception.SatpServerConnectFailedException;

/**
 * SATP协议客户端(单例)
 * 
 * @author Long.shangbo
 * 
 *         2014-2-25 下午8:40:09
 */
public class SatpClient {

	private static final SatpClient client = new SatpClient();
	
	private DatagramChannel channel = null;
	
	private String serverIP = null;
	
	private int serverPort = 0;
	
	private boolean isConnected = false;
	
	private Logger logger = Logger.getLogger(SatpClient.class);
	
	private SatpClient() {
		
	}

	/**
	 * 获得客户端
	 * 
	 * @return
	 */
	public static SatpClient getClient() {
		return client;
	}

	public boolean connect() throws SatpServerConnectFailedException{
		this.serverIP = UserArgsConfig.INSTANCE
				.getUserArgs(UserArgsConstant.LOWER_MACHINE_IP);
		this.serverPort = Integer.parseInt(UserArgsConfig.INSTANCE
				.getUserArgs(UserArgsConstant.LOWER_MACHINE_PORT));
		
		try {
			this.channel = DatagramChannel.open();
			this.channel.configureBlocking(false);
			this.channel.connect(new InetSocketAddress(serverIP, serverPort));
			this.isConnected = true;
			logger.info("Success to conneted the server<" + this.serverIP + "(" + this.serverPort + ")>");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			throw new SatpServerConnectFailedException(e);
		}
		
		return true;
	}
	
	/**
	 * 发送数据包
	 * 
	 * @param packet
	 * @throws IOException 
	 */
	public void sendData(SatpPacket packet) throws IOException{
		if(!isConnected)
				throw new IllegalConnectStateException("Server not connet...");
		
		this.channel.write(packet.getPacketBuffer());
	}
}
